package com.stylefeng.guns.order.service;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.api.cinema.CinemaServiceAPI;
import com.stylefeng.guns.api.cinema.vo.FilmInfoVO;
import com.stylefeng.guns.api.order.OrderServiceAPI;
import com.stylefeng.guns.api.order.vo.OrderQueryVO;
import com.stylefeng.guns.api.order.vo.OrderVO;
import com.stylefeng.guns.core.util.IdGenerator;
import com.stylefeng.guns.order.dao.MoocOrderTMapper;
import com.stylefeng.guns.order.model.MoocOrderT;
import com.stylefeng.guns.order.utils.FTPUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author dengwubo
 */
@Component
@Service(group = "default")
@Slf4j
public class DefaultOrderServiceImpl implements OrderServiceAPI {

    @Autowired
    private MoocOrderTMapper orderTMapper;
    @Reference
    private CinemaServiceAPI cinemaServiceAPI;

    @Autowired
    private FTPUtil ftpUtil;

    /**
     * 验证售出的票是否为真
     *
     * @param fieldId
     * @param seats
     * @return
     */
    @Override
    public boolean isTrueSeats(String fieldId, String seats) {
        // 根据FieldId找到对应的座位位置图
        String seatAddress = orderTMapper.getSeatsByFieldId(fieldId);
        // 读取位置图,判断seats是否为真
        String fileStrByAddress = ftpUtil.getFileStrByAddress(seatAddress);
        // 将fileStrByAddress转换为JSON对象
        JSONObject jsonObject = JSONObject.parseObject(fileStrByAddress);
        String ids = jsonObject.get("ids").toString();
        List<String> seatList = Arrays.asList(seats.split(","));
        List<String> idList = Arrays.asList(ids.split(","));
        boolean containsAll = idList.containsAll(seatList);
        if (containsAll){
            return true;
        }

        return false;
    }

    /**
     * 已经销售的座位里,有没有这些座位
     *
     * @param fieldId
     * @param seats
     * @return
     */
    @Override
    public boolean isNotSoldSeats(String fieldId, String seats) {
        EntityWrapper<MoocOrderT> wrapper = new EntityWrapper<>();
        wrapper.eq("field_id",fieldId);
        List<MoocOrderT> moocOrderTS = orderTMapper.selectList(wrapper);
        List<String> seatsIds = moocOrderTS.stream().map(order -> order.getSeatsIds().split(",")).flatMap(str -> Arrays.stream(str)).collect(Collectors.toList());
        List<String> seatList = Arrays.asList(seats.split(","));
        // 取集合交集,如存在交集则已选座位中存在已售座位
        Collection intersection = CollectionUtils.intersection(seatsIds, seatList);
        boolean empty = intersection.isEmpty();
        if (empty){
            return true;
        }
        return false;
    }

    /**
     * 创建订单信息
     *
     * @param fieldId
     * @param soldSeats
     * @param seatsName
     * @param userId
     * @return
     */
    @Override
    public OrderVO saveOrderInfo(Integer fieldId, String soldSeats, String seatsName, Integer userId) {
        // 编号
        String uuid = IdGenerator.genUuid();
        // 影片信息
        FilmInfoVO filmInfo = cinemaServiceAPI.getFilmInfoByFieldId(fieldId);
        Integer filmId = Integer.parseInt(filmInfo.getFilmId());

        // 获取场次信息
        OrderQueryVO orderNeeds = cinemaServiceAPI.getOrderNeeds(fieldId);
        Integer cinemaId = Integer.parseInt(orderNeeds.getCinemaId());
        double filmPrice = Double.parseDouble(orderNeeds.getFilmPrice());

        // 求订单总金额
        int solds = soldSeats.split(",").length;
        double totalPrice = getTotalPrice(solds,filmPrice);
        MoocOrderT moocOrderT = new MoocOrderT();
        moocOrderT.setUuid(uuid);
        moocOrderT.setSeatsName(seatsName);
        moocOrderT.setSeatsIds(soldSeats);
        moocOrderT.setOrderUser(userId);
        moocOrderT.setOrderPrice(totalPrice);
        moocOrderT.setFilmPrice(filmPrice);
        moocOrderT.setFilmId(filmId);
        moocOrderT.setFieldId(fieldId);
        moocOrderT.setCinemaId(cinemaId);

        Integer insert = orderTMapper.insert(moocOrderT);
        if (insert>0){
            OrderVO orderVO = orderTMapper.getOrderInfoById(uuid);
            return orderVO;
        }else{
            log.error("插入订单失败!");
            return null;
        }

    }

    private double getTotalPrice(int solds ,double filmPrice){
        BigDecimal price = BigDecimal.valueOf(filmPrice);
        BigDecimal amount = BigDecimal.valueOf(solds);
        // 小数点四舍五入
        BigDecimal totalPrice = price.multiply(amount).setScale(2,BigDecimal.ROUND_HALF_UP);
        double doubleTotalPrice = totalPrice.doubleValue();
        return doubleTotalPrice;
    }

    /**
     * 使用当前登陆人获取已经购买的订单
     *
     * @param userId
     * @return
     */
    @Override
    public Page<OrderVO> getOrderByUserId(Integer userId, Page<OrderVO> page) {
        Page<OrderVO> result = new Page<>();
        if (userId==null){
            log.error("订单查询业务失败,用户编号未传入");
            return null;
        }
        List<OrderVO> records = orderTMapper.getOrdersByUserId(userId,page);
        if (CollectionUtil.isEmpty(records)){
            result.setTotal(0);
            result.setRecords(new ArrayList<>());
            return result;
        }

        EntityWrapper<MoocOrderT> wrapper = new EntityWrapper<>();
        wrapper.eq("order_user",userId);
        Integer counts = orderTMapper.selectCount(wrapper);

        result.setTotal(counts);
        result.setRecords(records);
        return result;
    }

    /**
     * 根据FieldId 获取所有已经销售的座位编号
     *
     * @param fieldId
     * @return
     */
    @Override
    public String getSoldSeatsByFieldId(Integer fieldId) {

        if (fieldId == null){
            log.error("查询已售座位错误,未传入任何场次编号");
            return "";
        }
        String soldSeatsByFieldId = orderTMapper.getSoldSeatsByFieldId(fieldId);
        return soldSeatsByFieldId;
    }

    /**
     * 根据订单编号获取订单信息
     *
     * @param orderId
     * @return
     */
    @Override
    public OrderVO getOrderInfoById(String orderId) {

        OrderVO orderInfoById = orderTMapper.getOrderInfoById(orderId);

        return orderInfoById;
    }


    @Override
    public String getUserIdByOrder(String orderId) {

        String result = "";
        MoocOrderT moocOrderT = new MoocOrderT();
        moocOrderT.setUuid(orderId);
        moocOrderT = orderTMapper.selectOne(moocOrderT);
        if (moocOrderT!=null)
            result = moocOrderT.getOrderUser()+"";


        return result;
    }


    /**
     * 修改订单状态
     *
     * @param orderId
     * @return
     */
    @Override
    public boolean paySuccess(String orderId) {
        MoocOrderT moocOrderT = new MoocOrderT();
        moocOrderT.setUuid(orderId);
        moocOrderT.setOrderStatus(1);

        Integer integer = orderTMapper.updateById(moocOrderT);
        if (integer>=1)
            return true;
        return false;
    }

    @Override
    public boolean payFail(String orderId) {
        MoocOrderT moocOrderT = new MoocOrderT();
        moocOrderT.setUuid(orderId);
        moocOrderT.setOrderStatus(2);

        Integer integer = orderTMapper.updateById(moocOrderT);
        if (integer>=1)
            return true;
        return false;
    }
}
